/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Welcome.java
 *
 * Created on Dec 1, 2009, 2:31:43 PM
 */

/**
 *
 * @author lonex
 */

import java.awt.Container;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Vector;


public class Welcome extends JDialog
	implements ActionListener {
		
		
		/** Creates new form Welcome */
		public Welcome() {
			//Initialzing Peer Components
			try{
			    peer = new saperePeer();
				new pThread(peer).start(); //start the download server
			}
			catch (UnknownHostException e)
			{
				System.out.println("Unknown Host:"+e);
			}
		}
		
		public void initializeComponenets()
		{
			try{
				
				
				/****************************************************
				 * Initialization of the main Connection components
				 ****************************************************/
				
				t_serverIP           = new JTextField();
				f_serverIP           = new JLabel();
				t_serverPort         = new JTextField();
				f_serverPort         = new JLabel();
				connect              = new JButton();
				searchResults        = new JList();
				
				f_serverIP.setText  ("     Server IP Address");
				f_serverPort.setText("     Port No :");
				
				connect.setText("Connect");
				connect.addActionListener(new java.awt.event.ActionListener() {
										  public void actionPerformed(java.awt.event.ActionEvent evt) {
										  connectToServer(evt);
										  }});
				
				
				// peer    = new saperePeer();
				// peer.connect();
				
				
				/****************************************************
				 * Initialization of the main window components
				 ****************************************************/
				t_name            = new JTextField();
				t_email           = new JTextField();
				t_uName           = new JTextField();
				t_passwd          = new JPasswordField();
				f_name            = new JLabel();
				register          = new JButton();
				alreadyRegister   = new JButton();
				f_email           = new JLabel();
				f_uName           = new JLabel();
				f_passwd          = new JLabel();
				
				f_name.setText         ("     Name:      ");
				f_email.setText        ("     Email:     ");
				f_uName.setText        ("     User Name: ");
				f_passwd.setText       ("     Password:   ");
				register.setText       ("     Register    ");
				alreadyRegister.setText("Already Registerd");
				
				register.addActionListener(new java.awt.event.ActionListener() {
										   public void actionPerformed(java.awt.event.ActionEvent evt) {
										   registerActionPerformed(evt);
										   }
										   });
				alreadyRegister.addActionListener(new java.awt.event.ActionListener() {
												  public void actionPerformed(java.awt.event.ActionEvent evt) {
												  alreadyRegisterActionPerformed(evt);
												  }
												  });
				
				
				/****************************************************************
				 * Initialization of the login window components
				 ****************************************************************/
				t_login    = new JTextField();
				t_password = new JTextField();
				f_login    = new JLabel();
				f_password = new JLabel();
				signin     = new JButton();
				
				f_login.setText   ("   Login      :");
				f_password.setText("   Password   :");
				signin.setText("      Sign IN      ");
				
				
				signin.addActionListener(new java.awt.event.ActionListener() {
										 public void actionPerformed(java.awt.event.ActionEvent evt) {
										 singinActionPerformed(evt);
										 }
										 });
				
				
				
				
				/****************************************************
				 * Initialization of the Search Window Componenets
				 ****************************************************/
		        t_searchString  = new JTextField("Here",30);
				f_searchString  = new JLabel();
				f_shareFiles    = new JLabel();
				search          = new JButton();
				advertiseFiles  = new JButton();
				download = new JButton("   Download   ");
				search.setText        ("   Search    ");
				advertiseFiles.setText("  Advertise  ");
				
				// Search Function 
				search.addActionListener(new java.awt.event.ActionListener() {
										 public void actionPerformed(java.awt.event.ActionEvent evt) {
										 searchServer(evt);
										 }});
				// Advertise Function
				advertiseFiles.addActionListener(new java.awt.event.ActionListener() {
												 public void actionPerformed(java.awt.event.ActionEvent evt) {
												 advertiseToServer(evt);
												 }});
				
				
				
				
				
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
		}
		
		
		protected void  advertiseToServer(ActionEvent evt) {
			try
			{
				peer.advertise();
				
			}catch (Exception e)
			{
				System.out.println("Server IP/Port Incorrect");
				e.printStackTrace();
			}
			
			
			
		}
		
		protected void searchServer(ActionEvent evt) {
			try
			{
				Vector<String> results = peer.search(t_searchString.getText());
				for(int i =0;i<results.size();i++)
				{
					System.out.println((i+1)+": in client  "+results.get(i).toString());
				}
				searchResults = new JList(results);
				searchResults.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
				searchResults.setLayoutOrientation(JList.HORIZONTAL_WRAP);
				searchResults.setVisibleRowCount(-1);
				JScrollPane n = new JScrollPane(searchResults);
				//n.setPreferredSize(new Dimension(150,300));
				//add listerner here
				searchpanel.removeAll();
				searchpanel.add(n);
				searchpanel.updateUI();
				
			}catch (Exception e)
			{
				System.out.println("Server IP/Port Incorrect");
				e.printStackTrace();
			}
			
			
			
		}
		
		
		
		protected void connectToServer(ActionEvent evt) {
			try
			{
				//peer = new saperePeer(t_serverIP.getText(), Integer.parseInt(t_serverPort.getText()));
				peer.parent.server = InetAddress.getByName(t_serverIP.getText());
				peer.parent.port   = 4444;
				peer.connect();
				mainWindow();  
			}catch (Exception e)
			{
				System.out.println("Server IP/Port Incorrect");
				e.printStackTrace();
			}
			
			
			
		}
		
		public static void addComponentsToPane(Container pane) {
			
			
			
			GridLayout meLayout = new GridLayout(5,2,50,50);
			
			pane.setLayout(meLayout);
			pane.add(f_name);
			pane.add(t_name);
			pane.add(f_email);
			pane.add(t_email);
			pane.add(f_uName);
			pane.add(t_uName);
			pane.add(f_passwd);
			pane.add(t_passwd);
			pane.add(register);
			pane.add(alreadyRegister);
			
			
			
		}
		
		
		
		private static void createAndShowGUI() {
			//Create and set up the window.
			
			JFrame.setDefaultLookAndFeelDecorated(true);
			conWindow = new JFrame("Establish Connection");
			conWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			createConnectionWindow(conWindow.getContentPane());
			
			// Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			Dimension wndSize = Toolkit.getDefaultToolkit().getScreenSize(); 
			conWindow.setBounds(wndSize.width / 4, wndSize.height / 4, // Position
								wndSize.width / 2, wndSize.height / 2); // Size
			// frame.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);
			conWindow.setVisible(true);
			//Display the window.
			conWindow.pack();
			conWindow.setVisible(true);
		}
		
		private static void createConnectionWindow(Container pane) {
			// TODO Auto-generated method stub
			GridLayout meLayout = new GridLayout(0,2,50,50);
			pane.setLayout(meLayout);
			pane.add(f_serverIP);
			pane.add(t_serverIP);
			//pane.add(f_serverPort);
			//pane.add(t_serverPort);
			pane.add(connect);
			
		}
		
		
		
		public void mainWindow()
		{
			conWindow.setVisible(false);
			mainWindow = new JFrame("Registration Form");
			mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
			//Set up the content pane.
			addComponentsToPane(mainWindow.getContentPane());
			
			// set position and size
			
			// Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			Dimension wndSize = Toolkit.getDefaultToolkit().getScreenSize(); 
			mainWindow.setBounds(wndSize.width / 4, wndSize.height / 4, // Position
								 wndSize.width / 2, wndSize.height / 2); // Size
			// frame.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);
			mainWindow.setVisible(true);
			//Display the window.
			mainWindow.pack();
			mainWindow.setVisible(true);
			
		}
		
		public void createLoginWindow(Container pane)
		{
			
			mainWindow.setVisible(false);
			GridLayout meLayout = new GridLayout(3,2,50,50);
			pane.setLayout(meLayout);
			pane.add(f_login);
			pane.add(t_login);
			pane.add(f_password);
			pane.add(t_password);
			pane.add(signin);
		}
		
		public void LoginWindow()
		{
			mainWindow.setVisible(false);
			JFrame.setDefaultLookAndFeelDecorated(true);
			loginWindow = new JFrame("Login Window");
			loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
			//Set up the content pane.
			createLoginWindow(loginWindow.getContentPane());
			
			// set position and size
			
			// Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			Dimension wndSize = Toolkit.getDefaultToolkit().getScreenSize(); 
			loginWindow.setBounds(wndSize.width / 4, wndSize.height / 4, // Position
								  wndSize.width / 2, wndSize.height / 2); // Size
			// frame.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);
			loginWindow.setVisible(true);
			//Display the window.
			loginWindow.pack();
			loginWindow.setVisible(true);
			
		}
		
		
		/*****************************************************************************
		 * Create Search Window
		 *****************************************************************************/
		
		public void createSearchWindow(Container pane)
		{
			
		    loginWindow.setVisible(false);
			//
			//GridLayout meLayout = new GridLayout(5,2,50,50);
			BorderLayout meLayout = new BorderLayout();
			JPanel top = new JPanel();
			top.setLayout(new FlowLayout());
			f_searchString.setText(" Search Text ");
			//	f_shareFiles.setText(" Share Files " );
			top.add(f_searchString);
			top.add(t_searchString);
			
			JPanel west = new JPanel();
			west.add(f_shareFiles);
			west.add(search);
			west.add(download);
			searchpanel = new JPanel();
			searchpanel.setBackground(Color.red);
			searchpanel.add(searchResults);
			pane.setLayout(meLayout);
			//pane.add(t_searchString);
			//pane.add(f_shareFiles);
			//pane.add(search );
			pane.add(top,"North");
			pane.add(west,"East");
			pane.add(searchpanel);
            pane.add(advertiseFiles,"South");
		}
		
		public void searchWindow()
		{
			mainWindow.setVisible(false);
			JFrame.setDefaultLookAndFeelDecorated(true);
			searchWindow = new JFrame(" Search Window ");
			searchWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
			//Set up the content pane.
			createSearchWindow(searchWindow.getContentPane());
			
			// set position and size
			
			// Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			Dimension wndSize = Toolkit.getDefaultToolkit().getScreenSize(); 
			searchWindow.setBounds(wndSize.width / 4, wndSize.height / 4, // Position
								   wndSize.width / 2, wndSize.height / 2); // Size
			// frame.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);
			searchWindow.setVisible(true);
			//Display the window.
			searchWindow.pack();
			searchWindow.setVisible(true);
			
		}
		
		
		
		
		
		
		
		
		
		
		
		public void actionPerformed(ActionEvent e) {
			
		}
		private void registerActionPerformed(java.awt.event.ActionEvent evt) {
			try{
				User regMe = new User();
				if(t_name.getText().equals("") && t_email.getText().equals("") && t_passwd.getText().equals("") && t_uName.getText().equals(""))
				{
					System.out.println("Its empty");
				}
				else
				{
					regMe.name   = t_name.getText();
					regMe.email  = t_email.getText();
					regMe.pass   = t_passwd.getText();
					regMe.userID = t_uName.getText();
					peer.register(regMe);
					
				}
				
				LoginWindow();
				System.out.println("Registeration called");
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			// TODO add your handling code here:
		}
		public void  alreadyRegisterActionPerformed (java.awt.event.ActionEvent evt) {
			LoginWindow();
		}
		// Sign in action performed 
		public void singinActionPerformed(java.awt.event.ActionEvent evt) {
			try
			{
				peer.login(t_login.getText(), t_password.getText()); 
				searchWindow();
				
				
			}catch (Exception e)
			{
				System.out.println("Login/Password Incorrect");
				e.printStackTrace();
			}
		}
		
		public static void main(String[] args) {
			
			Welcome gui = new Welcome();
			gui.initializeComponenets();
			
			//Schedule a job for the event-dispatching thread:
			//creating and showing this application's GUI.
			javax.swing.SwingUtilities.invokeLater(new Runnable() {
												   public void run() {
												   createAndShowGUI();
												   }
												   });
		}
		
		/*************************************************
		 * Connect Window
		 ************************************************/
		private static javax.swing.JFrame          conWindow;
		private static javax.swing.JTextField      t_serverIP;
		private static javax.swing.JLabel          f_serverIP;
		private static javax.swing.JTextField      t_serverPort;
		private static javax.swing.JLabel          f_serverPort;
		private static javax.swing.JButton         connect;					  
		
		
		
		/*************************************************
		 * Main Window variables
		 ************************************************/
		// Variables declaration - do not modify
		private static javax.swing.JFrame          mainWindow;
		private static javax.swing.JTextField      t_name;
		private static javax.swing.JTextField      t_email;
		private static javax.swing.JTextField      t_uName;
		private static javax.swing.JPasswordField  t_passwd;
		private static javax.swing.JLabel          f_name;
		private static javax.swing.JLabel          f_email;
		private static javax.swing.JLabel          f_uName;
		private static javax.swing.JLabel          f_passwd;
		private static javax.swing.JButton         register;
		private static javax.swing.JButton         alreadyRegister;
		private static saperePeer                  peer;
		
		/***************************************************
		 * Static Variables for login window    
		 ***************************************************/
		private static javax.swing.JFrame      loginWindow;
		private static javax.swing.JTextField  t_login;
		private static javax.swing.JTextField  t_password;
		private static javax.swing.JLabel      f_login;
		private static javax.swing.JLabel      f_password;
		private static javax.swing.JButton     signin;
		
		/***************************************************
		 * Static Variables for Search and Download   
		 ***************************************************/
		private static javax.swing.JPanel searchpanel;
		private static javax.swing.JFrame      searchWindow;
		private static javax.swing.JTextField  t_searchString;
		private static javax.swing.JLabel      f_searchString;
		private static javax.swing.JLabel      f_shareFiles;
		private static javax.swing.JButton     search;
		private static javax.swing.JButton download;
		private static javax.swing.JButton     advertiseFiles;
		private static javax.swing.JList       searchResults; 
		
		
		
		// End of variables declaration
		
	}